/**
 * Created by ybjaa on 2017/4/20.
 */
import {Component, OnInit} from '@angular/core';
import {Menu} from "../model/Menu";
import {MenusService} from "./menus.service";
import {MenuHandleEnum} from "../model/MenuHandleEnum";
import {MenuHandle} from "../model/MenuHandle";
import {ArrayModel} from "../model/ArrayModel";
import {BaseComponent} from "../base.component";
import {ResponseData} from "../model/ResponseData";

declare const $ :any;

@Component({
    selector: 'my-rightContent',
    templateUrl:"./menu.component.html",
    styleUrls:["./menu.component.css"],
})
export class MenuManageComponent extends BaseComponent implements OnInit {


    currentMenuHandle:MenuHandleEnum=null;
    _arrayMenus:ArrayModel<Menu>=new ArrayModel(Menu);

    _isHttp:boolean=false;

    updateMenu:Menu =new Menu();

    get ArrayMenus():Menu[]{
        return this._arrayMenus.Datasource;
    }



    ngOnInit(): void {

        let parent=this;
        this.isAjax=true;

        this.menuService.getAllMenus()
            .then(response=>{
                parent.isAjax=false;
                if(response.result){
                    parent._arrayMenus.Datasource=response.data;
                }else {
                    parent.setMessage(null,response.message);
                }

            })
            .catch(ex=>parent.setMessage(ex));
    }

    constructor(private menuService:MenusService){super()};


    selectMenu(menu:Menu)
    {
        this.currentMenuHandle=MenuHandleEnum.Update;
        this.updateMenu=menu.clone();
    }


    /**
     * 和服务器的交互
     *
     */
    protected handleMenu()
    {
        this._message="";
        let parent=this;

        parent.isAjax=true;

        switch (parent.currentMenuHandle)
        {

            case  MenuHandleEnum.CreateTop:
                this.menuService.createMenu(this.updateMenu)
                    .then(response=>{
                        parent.isAjax=false;
                        parent.aJAXResponseHandle(response);
                        if(response.result)
                        {
                            $('#myModal').modal('hide');
                            let newMenu=parent.updateMenu.clone();
                            newMenu.ID=response.data;
                            parent.ArrayMenus.push(newMenu);
                        }
                    })
                    .catch(ex=>parent.setMessage(ex));
                break;

            case  MenuHandleEnum.Create:
                parent.menuService.createMenu(parent.updateMenu)
                    .then(response=>{
                        parent.aJAXResponseHandle(response);
                        if(response.result)
                        {
                            $('#myModal').modal('hide');
                            let newMenu=parent.updateMenu.clone();
                            newMenu.ID=response.data;
                            parent.addMenuToArray(newMenu,parent.ArrayMenus);
                        }
                    })
                    .catch(ex=>parent.setMessage(ex));
                break;



            case MenuHandleEnum.Delete:
                parent.menuService.deleteMenu(parent.updateMenu.ID)
                    .then(response=>{
                        parent.aJAXResponseHandle(response);
                        if(response.result)
                        {
                            $('#warming').modal('hide');
                            parent._arrayMenus.Datasource=parent.deleteMenuToArray(parent.updateMenu.ID,parent.ArrayMenus);
                        }
                    })
                    .catch(ex=>parent.setMessage(ex));
                break;


            case  MenuHandleEnum.Update:
                parent.menuService.updateMenu(parent.updateMenu)
                    .then(response=>{
                        parent.aJAXResponseHandle(response);
                        if(response.result)
                        {
                            $('#myModal').modal('hide');
                            let newMenu=parent.updateMenu.clone();
                            parent.updateMenuToArray(newMenu,parent.ArrayMenus);
                        }
                    })
                    .catch(ex=>parent.setMessage(ex));
                break;


            case  MenuHandleEnum.Up:
                parent.menuService.sortMenu(parent.updateMenu,"UP")
                    .then(response=>{
                        parent.aJAXResponseHandle(response);
                        if(response.result)
                        {
                            parent.sortMenuToArray(parent.ArrayMenus,parent.updateMenu.ID,MenuHandleEnum.Up);
                        }
                    })
                    .catch(ex=>parent.setMessage(ex));

                break;


            case  MenuHandleEnum.Down:
                parent.menuService.sortMenu(parent.updateMenu,"Down")
                    .then(response=>{
                        parent.aJAXResponseHandle(response);
                        if(response.result)
                        {
                            parent.sortMenuToArray(parent.ArrayMenus,parent.updateMenu.ID,MenuHandleEnum.Down);
                        }
                    })
                    .catch(ex=>parent.setMessage(ex));
                break;

            default:
                parent.isAjax=false;
                break;
        }




    }


    /**
     * 对返回值的操作
     * @constructor
     */
    private aJAXResponseHandle(response:ResponseData<any>)
    {
        this.isAjax=false;

        if(!response.result)
        {
            this.setMessage(null,response.message);
        }

    }


    /**
     * 消息错误时设置错误信息
     * @param ex
     * @param message
     */
    protected setMessage(ex:TypeError,message:string=null):void
    {

        if(this&&this.currentMenuHandle&&(this.currentMenuHandle===(MenuHandleEnum.Up||MenuHandleEnum.Down))){
            this.isAjax=false;
            $("#error").modal("show");
        }

        super.setMessage(ex,message);

    }

    /**
     * 向数据源添加数据
     * @param menu
     * @param menus
     */
    protected addMenuToArray(menu:Menu,menus:Menu[])
    {
        for( let m of menus )
        {
            if(m.ID===menu.parentID)
            {
                if(!m.children) m.children=[];
                m.children.push(menu);
                return;
            }
            else
            {
                if(m.children&&m.children.length>0) this.addMenuToArray(menu,m.children);
            }
        }


    }


    /**
     * 向数据源删除数据
     * @param id 要删除的id
     * @param menus
     */
    protected deleteMenuToArray(id:number,menus:Menu[])
    {
        return menus.filter((m)=>{

            if(m.ID===id)
            {
                return false;
            }

            if(m.children&&m.children.length>0)
            {
                m.children= this.deleteMenuToArray(id,m.children);
            }

            return true;
        });

    }


    /**
     * 向数据源修改数据
     * @param menu
     * @param menus
     */
    protected updateMenuToArray(menu:Menu,menus:Menu[])
    {

        for(let m of menus){

            if(m.ID===menu.ID)
            {
                m.copyFrom(menu);
                return;
            }

            if(m.children&&m.children.length>0)
            {
                this.updateMenuToArray(menu,m.children);
            }
        }

    }


    /**
     * 向数据源的数据进行排序
     * @param menus
     * @param id
     * @param type 向上排序还是向下排序（UP,Down）
     */
    protected sortMenuToArray(menus:Menu[],id:number,type:MenuHandleEnum)
    {

        for(let i=0;i<menus.length;i++){
            if(menus[i].ID===id){
                if(type===MenuHandleEnum.Up){
                    if(i===0||menus.length<=1) return;
                    let menu=menus[i];
                    menus[i]=menus[i-1];
                    menus[i-1]=menu;
                }else if(type===MenuHandleEnum.Down){
                    if(i===menus.length||menus.length<=1) return;
                    let menu=menus[i];
                    menus[i]=menus[i+1];
                    menus[i+1]=menu;
                }
                return;
            }


            if(menus[i].children&&menus[i].children.length>0)
            {
                this.sortMenuToArray(menus[i].children,id,type);
            }

        }

    }



    protected createMenu(menu:Menu)
    {
        this.createTopMenu();
        this.currentMenuHandle=MenuHandleEnum.Create;
        this.updateMenu.parentID=menu.ID;
    }

    protected createTopMenu()
    {

        this.currentMenuHandle=MenuHandleEnum.CreateTop;

        this.updateMenu=new MenuHandle();
        this.updateMenu.parentID=0;
        this.updateMenu.isWrite=true;
        this.updateMenu.isDelete=true;
    }

    /**
     * 删除
     * @param menu
     */
    protected deleteMenu(menu:Menu)
    {
        this.currentMenuHandle=MenuHandleEnum.Delete;
        this.updateMenu=menu.clone();
    }

    protected downMenu(menu:Menu){
        this.currentMenuHandle=MenuHandleEnum.Down;
        this.updateMenu=menu.clone();
        this.handleMenu();
    }

    protected upMenu(menu:Menu){
        this.currentMenuHandle=MenuHandleEnum.Up;
        this.updateMenu=menu.clone();
        this.handleMenu();
    }




}


